/**
 * 
 */
package com.kexinde.wjifen.action;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.kexinde.wjifen.dao.GiftExchangeDao;
import com.kexinde.wjifen.model.User;
import com.kexinde.wjifen.util.CreateRandomNum;
import com.kexinde.wjifen.vo.GiftDetail;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author vincent
 * 
 */
public class ShoppingListAction extends ActionSupport implements SessionAware,
		RequestAware {

	private final static Logger logger = Logger
			.getLogger(ShoppingListAction.class);
	private Map<String, Object> session;
	private Map<String, Object> request;

	private int itemIndex; // 商品索引（ps：非Id，是在shopingList中的index）
	private long totalPoint; // 合计积分
	private int outOfBoundIndex;// 越界的商品索引
	private String exchangeId;	//兑换记录编号

	/**
	 * 提交订单
	 * 
	 * @return
	 */
	public String submitOrder() { // 未完善
		try {
			User user = (User) session.get("user");
			if (user != null) { // 已经登录
				List<GiftDetail> shoppingList = (List<GiftDetail>) session
				.get("shoppingList");
				exchangeId = CreateRandomNum.create(15);
				totalPoint = this.calculateTotal(shoppingList);
				user.setTotalPoint(user.getTotalPoint()-totalPoint);
				session.remove("shoppingList");
				return SUCCESS;

			} else { // 未登录，跳转至登录页面
				return ERROR;
			}
		} catch (Exception ex) {
			logger.error(ex);
			return ERROR;
		}
	}

	/**
	 * 结算按钮
	 * 
	 * @return
	 */
	public String settleAccounts() {// 地址部分未完善
		try {
			User user = (User) session.get("user");
			if (user != null) { // 已经登录
				List<GiftDetail> shoppingList = (List<GiftDetail>) session
						.get("shoppingList");
				outOfBoundIndex = this.checkStocks(shoppingList);
				totalPoint = this.calculateTotal(shoppingList);
				if (outOfBoundIndex == -1) {// 库存足够
					if (user.getTotalPoint() >= totalPoint) {// 总分足够

						return SUCCESS;

					} else {// 总分不足
						request.put("feedbackMsg", "总分不足");
						return SUCCESS;
					}

				} else {// 库存不足
					int stocks = shoppingList.get(outOfBoundIndex).getStocks();
					request.put("feedbackMsg", "库存不足,仅剩余:" + stocks);
					request.put("forbidSubmit", "禁止提交");
					return SUCCESS;
				}

			} else { // 未登录，跳转至登录页面
				return ERROR;
			}
		} catch (Exception ex) {
			logger.error(ex);
			return ERROR;
		}
	}

	/**
	 * 兑换车中的加按钮
	 * 
	 * @return
	 */
	public String plus() {
		try {
			if (session.get("user") != null) { // 已经登录
				List<GiftDetail> shoppingList = (List<GiftDetail>) session
						.get("shoppingList");
				GiftDetail gift = shoppingList.get(itemIndex);
				gift.setNum(gift.getNum() + 1);
				shoppingList.set(itemIndex, gift);
				session.put("shoppingList", shoppingList);
				totalPoint = calculateTotal(shoppingList);
				return SUCCESS;
			} else { // 未登录，跳转至登录页面
				return ERROR;
			}
		} catch (Exception ex) {
			logger.error(ex);
			return ERROR;
		}
	}

	/**
	 * 兑换车中的减按钮
	 * 
	 * @return
	 */
	public String minus() {
		try {
			if (session.get("user") != null) { // 已经登录
				List<GiftDetail> shoppingList = (List<GiftDetail>) session
						.get("shoppingList");
				GiftDetail gift = shoppingList.get(itemIndex);
				int num = gift.getNum() - 1;
				if (num < 1)
					num = 1;
				gift.setNum(num);
				shoppingList.set(itemIndex, gift);
				session.put("shoppingList", shoppingList);
				totalPoint = calculateTotal(shoppingList);
				return SUCCESS;
			} else { // 未登录，跳转至登录页面
				return ERROR;
			}
		} catch (Exception ex) {
			logger.error(ex);
			return ERROR;
		}
	}

	/**
	 * 兑换车中的删除按钮
	 * 
	 * @return
	 */
	public String deleteItem() {
		try {
			if (session.get("user") != null) { // 已经登录，删除相应item
				List<GiftDetail> shoppingList = (List<GiftDetail>) session
						.get("shoppingList");
				shoppingList.remove(itemIndex);
				totalPoint = calculateTotal(shoppingList);
				return SUCCESS;
			} else { // 未登录，跳转至登录页面
				return ERROR;
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return ERROR;
	}

	/**
	 * 打开兑换车
	 * 
	 * @return
	 */
	public String shoppingList() {
		try {
			if (session.get("user") != null) { // 已经登录
				List<GiftDetail> shoppingList = (List<GiftDetail>) session
						.get("shoppingList");
				if (shoppingList != null)
					totalPoint = calculateTotal(shoppingList);
				return SUCCESS;
			} else { // 未登录，跳转至登录页面
				return ERROR;
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return ERROR;
	}

	/**
	 * 计算合计积分
	 * 
	 * @return
	 */
	private long calculateTotal(List<GiftDetail> list) {
		long total = 0;
		for (GiftDetail giftDetail : list) {
			total += giftDetail.getNum() * giftDetail.getPoint();
		}
		return total;
	}

	/**
	 * 检查商品库存是否足够
	 * 
	 * @return -1代表库存足够
	 */
	private int checkStocks(List<GiftDetail> list) {
		int index = -1;
		for (GiftDetail giftDetail : list) {
			if (giftDetail.getStocks() < giftDetail.getNum()) {
				index = list.indexOf(giftDetail);
				break;
			}
		}
		return index;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public int getItemIndex() {
		return itemIndex;
	}

	public void setItemIndex(int itemIndex) {
		this.itemIndex = itemIndex;
	}

	public long getTotalPoint() {
		return totalPoint;
	}

	public void setTotalPoint(long totalPoint) {
		this.totalPoint = totalPoint;
	}

	@Override
	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}

	public int getOutOfBoundIndex() {
		return outOfBoundIndex;
	}

	public void setOutOfBoundIndex(int outOfBoundIndex) {
		this.outOfBoundIndex = outOfBoundIndex;
	}

	public String getExchangeId() {
		return exchangeId;
	}

	public void setExchangeId(String exchangeId) {
		this.exchangeId = exchangeId;
	}

}
